import Router from 'koa-router'
import Email from 'nodemailer'
import UserModel from './dbs/user'
import CodeModel from './dbs/code'
const check = require("../middleware/user")
// 前缀
const router = new Router({
  prefix: '/users'
})

// 验证用户名是否存在

router.post('/checkName', async (ctx) => {
  const { name } = ctx.request.body
  const user = await UserModel.find({ name })
  if (user.length) {
    ctx.body = {
      code: -1,
      msg: '用户名已存在'
    }
  } else {
    ctx.body = {
      code: 1,
      msg: '用户名可用'
    }
  }
})

// 注册
router.post('/register', async (ctx) => {
  const { name, password, email, code } = ctx.request.body
  const user = await UserModel.find({ name })
  const ucode = await CodeModel.findOne({ name })
  if (user.length) {
    ctx.body = {
      code: -1,
      msg: '用户名已存在'
    }
    return
  }
  if (code !== ucode.code) {
    ctx.body = { code: -1, msg: '验证码错误' }
  } else {
    const nuser = await UserModel.create({ name, password, email })
    if (nuser) {
      ctx.body = {
        code: 1,
        msg: '注册成功'
      }
    }
  }
})
// 登录
router.post('/login', async (ctx) => {
  const fuser = await UserModel.find({ name: ctx.request.body.name })
  if (fuser.length) {
    if (fuser[0].password === ctx.request.body.password) {
      ctx.session.username = fuser[0].name
      ctx.body = {
        code: 1,
        msg: '登录成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: "密码错误"
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: "用户不存在"
    }
  }
})
// 获取用户
router.get('/getUser', check, (ctx) => {
  const username = ctx.session.username
  ctx.body = {
    code: 1,
    username
  }
})
// 注销
router.get('/exit', check, (ctx) => {
  ctx.session = null
  ctx.body = { code: 1, msg: '注销成功' }
})
// 发送验证码
router.get('/sendCode', async (ctx) => {
  const name = ctx.query.name
  const email = ctx.query.email
  const code = Math.random().toString().slice(2, 8)
  const ncode = await CodeModel.create({ name, code, createdAt: new Date() })
  if (ncode) {
    const transport = Email.createTransport({
      service: 'qq',
      auth: {
        user: '869403180@qq.com',
        pass: '填写自己的QQ邮箱授权码'
      }
    })
    // 发送
    const success = await transport.sendMail({
      from: '869403180@qq.com',
      to: email,
      subject: 'LLA认证',
      text: `你的验证码是${code}`
    })
    if (success) {
      ctx.body = { code: 1, msg: '已成功发送验证码' }
    }
  } else {
    ctx.body = { code: -1, msg: '验证码写入数据库失败' }
  }
})

router.get("/test", (ctx) => {
  if (ctx.session.count === null) {
    ctx.session.count = 0
  }
  ctx.session.count++
  ctx.body = {
    count: ctx.session.count
  }
})
export default router
